package com.AppliGestion.client.RuleMakingSystem;

import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellSavedEvent;
import com.smartgwt.client.widgets.grid.events.CellSavedHandler;
import com.AppliGestion.shared.model.RuleMakingSystem.data.Data;
import com.AppliGestion.shared.model.RuleMakingSystem.data.TypeData;

public class DataListGrid extends ListGrid{
	public DataListGrid() {
		super();
		setWidth(250);
		setHeight(100);
		setShowAllRecords(true);
		setSelectionType(SelectionStyle.MULTIPLE);
		
		
		ListGridField labelField = new ListGridField("label", "Label");
		labelField.setType(ListGridFieldType.TEXT);
		labelField.addCellSavedHandler(new CellSavedHandler() {
			
			public void onCellSaved(CellSavedEvent event) {
				if(!verifyKey((String) event.getNewValue())){
					SC.warn("Le label "+event.getNewValue()+"est déjà utilisé dans la liste");
					((DataRecord) getSelectedRecord()).setLabel((String) event.getOldValue());
				}		
				
			}
		});
			
		
		ListGridField isParamField = new ListGridField("isParam", "Parametre");
		isParamField.setType(ListGridFieldType.BOOLEAN);
		ListGridField typeDataField = new ListGridField("type", "Type");
		typeDataField.setType(ListGridFieldType.TEXT);
		typeDataField.setValueMap(TypeData.getValueMap());
		ListGridField valueField = new ListGridField("value", "Valeur");
		valueField.setType(ListGridFieldType.TEXT);		
		
		setFields(labelField,isParamField,typeDataField,valueField);
	
	}
	
	public boolean verifyKey(String label){
		for(ListGridRecord gridRecord : getRecords()){
			if(gridRecord.getAttributeAsString("label").equals(label))	return false;
		}
		return true;
	}
	
	public void setData(Data data) {
		for(String label : data.getLabel())	addData(new DataRecord(label, data.get(label)));	
	}

	
	
	public void addData(String label){
		addData(new DataRecord(label,false,TypeData.NUMERIC.toString(),null));
	}

	public void addData(ListGridRecord[] selection) {
		for(ListGridRecord record : selection) addData(record);		
	}	
	
	
	/*	
	public Data getData(){
		Data data = new Data();
		for(ListGridRecord gridRecord : getRecords()){
			if(((TypeData) gridRecord.getAttributeAsObject("type")).equals(TypeData.NUMERIC)){
			data.put(gridRecord.getAttributeAsString("label"),
					 gridRecord.getAttributeAsDouble("value"),
					 gridRecord.getAttributeAsBoolean("isParam"));
			}else{
				data.put(gridRecord.getAttributeAsString("label"),
						 gridRecord.getAttributeAsString("value"),
						 gridRecord.getAttributeAsBoolean("isParam"));
			}
		}
		return data;
	}
	*/	
}
